<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt or that can be found at 
 * http://code.google.com/p/billboardce/wiki/License.
 *
 * @package    Device
 * @category   Model
 * @license    http://code.google.com/p/billboardce/wiki/License New BSD License
 * @version    SVN: $Id: $
 */
class Device extends Ot_Db_Table
{
    /**
     * Name of the table in the database
     *
     * @var string
     */
    protected $_name = 'tbl_device';
  
    /**
     * Primary key of the table
     *
     * @var string
     */
    protected $_primary = 'deviceId';
    
    protected $_deviceTypes = array(
                'unspecified' => 'Unspecified',
                'television'  => 'Television',
                'computer'    => 'Computer',
                'ipad'        => 'iPad',
                'iphone'      => 'iPhone',
                'other'       => 'Other'
             );
    
    public function getDevicesForAccount($accountId, $enabledOnly = true)
    {
         $where = $this->getAdapter()->quoteInto('accountId = ?', $accountId);
         
         if ($enabledOnly) {
             $where .= ' AND '
                     . $this->getAdapter()->quoteInto('enabled = ?', 1);
         }
         
         return $this->fetchAll($where, 'name');
    }
    
    public function getUnassignedDevices($accountId)
    {
        $slidestream = new Slidestream();
        $slidestreamDevice = new Slidestream_Device();

        $slidestreams = $slidestream->getSlidestreamsForAccount($accountId);
        
        $slidestreamIds = array();
        foreach ($slidestreams as $s) {
            $slidestreamIds[] = $s->slidestreamId;
        }
        
        $where = $this->getAdapter()->quoteInto('accountId = ?', $accountId);
        $allDevices = $this->fetchAll($where);
        
        $deviceList = array();
        
        foreach ($allDevices as $d) {
            $deviceList[$d->deviceId] = $d->toArray();
        }
        
        $where = $this->getAdapter()->quoteInto('slidestreamId IN (?)', $slidestreamIds);
        $assignedDevices = $slidestreamDevice->fetchAll($where);
        
        // unassigned devices is the diff between $devices and $assignedDevices
        foreach ($assignedDevices as $a) {
            if (isset($deviceList[$a->deviceId])) {
                unset($deviceList[$a->deviceId]);
            }
        }
        
        return $deviceList;
        
    }
    
    public function getDeviceTypes()
    {
        return $this->_deviceTypes;
    }
    
    public function getDeviceTypeName($type) {
        if (isset($this->_deviceTypes[$type])) {
            return $this->_deviceTypes[$type];
        } else {
            return false;
        }
    }
    
    /**
     * Generates the form for adding and editing a device
     * 
     * @param array $values The values the form should be populated with
     * @return Zend_Form
     */
    public function form ($values = array())
    {
        $form = new Zend_Form();
        $form->setAttrib('id', 'deviceForm')
             ->setDecorators(array(
                     'FormElements',
                     array('HtmlTag', array('tag' => 'div', 'class' => 'zend_form')),
                     'Form',
             ));
                
        $name = $form->createElement('text', 'name', array('label' => 'Name:'));
        $name->setRequired(true)
             ->addFilter('StringTrim')
             ->addFilter('StripTags')
             ->setAttrib('maxlength', 64)
             ->setValue((isset($values['name'])) ? $values['name'] : '')
             ->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => 'Must not be blank!')));
             
        $ip = $form->createElement('text', 'ip', array('label' => 'IP:'));
        $ip->setRequired(true)
           ->addFilter('StringTrim')
           ->addFilter('StripTags')
           ->setAttrib('maxlength', 15)
           ->setValue((isset($values['ip'])) ? $values['ip'] : '')
           ->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => 'Must not be blank!')));

        $description = $form->createElement('text', 'description', array('label' => 'Description:'));
        $description->setRequired(false)
                    ->addFilter('StringTrim')
                    ->addFilter('StripTags')
                    ->setAttrib('maxlength', 255)
                    ->setValue((isset($values['description'])) ? $values['description'] : '');
        
        $type = $form->createElement('select', 'type', array('label' => 'Type:'));
        $type->setRequired(false)
             ->setMultiOptions($this->_deviceTypes)
             ->setValue((isset($values['type'])) ? $values['type'] : 'unspecified');

        $enabled = $form->createElement('select', 'enabled', array('label' => 'Status:'));
        $enabled->setRequired(false)
             ->setMultiOptions(array(
                1 => 'Enabled',  
                0 => 'Disabled'
             ))
             ->setValue((isset($values['enabled'])) ? $values['enabled'] : 1);
             
        $address = $form->createElement('text', 'address', array('label' => 'Address:'));
        $address->setRequired(false)
                ->addFilter('StringTrim')
                ->addFilter('StripTags')
                ->setAttrib('maxlength', 255)
                ->setValue((isset($values['address'])) ? $values['address'] : '');

        $lat = $form->createElement('text', 'lat', array('label' => 'Latitude:'));
        $lat->setRequired(false)
            ->addFilter('StringTrim')
            ->addFilter('StripTags')
            ->setValue((isset($values['lat'])) ? $values['lat'] : '');
        
        $lng = $form->createElement('text', 'lng', array('label' => 'Longitude:'));
        $lng->setRequired(false)
            ->addFilter('StringTrim')
            ->addFilter('StripTags')
            ->setValue((isset($values['lng'])) ? $values['lng'] : '');
           
        $submit = $form->createElement('submit', 'submitButton', array('label' => 'Submit'));
        $submit->setDecorators(array(
                   array('ViewHelper', array('helper' => 'formSubmit'))
                 ));

        $cancel = $form->createElement('button', 'cancel', array('label' => 'Cancel'));
        $cancel->setAttrib('id', 'cancel');
        $cancel->setDecorators(array(
                   array('ViewHelper', array('helper' => 'formButton'))
                ));
        
        $form->addElements(array($name, $ip, $description, $type, $enabled, $address, $lat, $lng));

        $form->setElementDecorators(array(
                  'ViewHelper',
                  'Errors',
                  array('HtmlTag', array('tag' => 'div', 'class' => 'elm')),
                  array('Label', array('tag' => 'span')),
              ))
             ->addElements(array($submit, $cancel));

        if (isset($values['deviceId'])) {

            $deviceId = $form->createElement('hidden', 'deviceId');
            $deviceId->setValue($values['deviceId']);
            $deviceId->setDecorators(array(
                array('ViewHelper', array('helper' => 'formHidden'))
            ));

            $form->addElement($deviceId);
        }
        return $form;
    }
}